package com.wms.presenters;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Locale;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.gatech.wms.R;
import com.wms.assets.Categories;
import com.wms.assets.Item;
import com.wms.model.ItemsModel;

/**
 * Activity that manages the search functions for the app.
 * @author Nathan
 */
public class SearchScreenActivity extends WMSActivity {
	
	private static final String TAG = "WMS";
	private ItemsModel model;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_screen);
		model = ItemsModel.getInstance();
		setupButtons();
	}
	
	private void setupButtons() {
		Button submit = (Button)findViewById(R.id.searchButtonSubmit);
		submit.setOnClickListener(new OnSubmitClick());
		
		Spinner view = (Spinner)findViewById(R.id.searchCatSpinner);
		view.setAdapter(new ArrayAdapter<String>(this, R.layout.item_renderer, Categories.list));
	}
	
	private void populateItemsFromQuery(String name, String cat, String loc) {
		ListView view = (ListView)this.findViewById(R.id.searchResultsList);
		ArrayList<String> names = new ArrayList<String>();
		ArrayList<Item> items = null;
		try {
			items = model.getFilteredItems(name, cat, loc);
		} catch (Exception e) {
			Toast msg = Toast.makeText(this, "Error Retrieving Items from Database", Toast.LENGTH_LONG);
			msg.show();
		} 
		
		
		
		
		for (Item it : items) {
			names.add(it.getName());
		}
		
		String[] strings = new String[names.size()];
		names.toArray(strings);
		view.setAdapter(new ArrayAdapter<String>(this, R.layout.item_renderer, strings));
	}
	
	
	
	private class OnSubmitClick implements View.OnClickListener {
		@Override
		public void onClick(View v) {
			final EditText searchText = (EditText)findViewById(R.id.searchTextView);
			final String query = (String)searchText.getText().toString();
			
			final Spinner catSpin = (Spinner)findViewById(R.id.searchCatSpinner);
			final String cat = (String)catSpin.getSelectedItem().toString();
			
			final EditText locText = (EditText)findViewById(R.id.searchLocationText);
			final String loc = (String)locText.getText().toString();
			populateItemsFromQuery(query, cat, loc);
		}
	}
	
}
